package org.vincen.jarvis.files.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.vincen.jarvis.files.pojo.Employee;

@Repository
public class EmployeeDao {
	@PersistenceUnit(unitName="EmployeeService")
    protected EntityManager em;

    public EntityManager getEntityManager(){
    	return em;
    }

    public Employee createEmployee(int id, String name, int salary) {
        Employee emp = new Employee(id);
        emp.setName(name);
        emp.setSalary(salary);
        getEntityManager().persist(emp);
        return emp;
    }

    public Employee removeEmployee(int id) {
        Employee emp = findEmployee(id);
        if (emp != null) {
        	getEntityManager().remove(emp);
        	return emp;
        } else {
        	return null;
        }
    }

    public Employee raiseEmployeeSalary(int id, int raise) {
    	Employee emp = findEmployee(id);
        if (emp != null) {
            emp.setSalary(emp.getSalary() + raise);
        }
        return emp;
    }

    public Employee findEmployee(int id) {
        return getEntityManager().find(Employee.class, id);
    }

    @SuppressWarnings("unchecked")
	public List<Employee> findAllEmployees() {
        Query query = getEntityManager().createQuery("SELECT e FROM Employee e");
        return (List<Employee>) query.getResultList();
    }
}
